package com.mini.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mini.conditon.ChanceBaseCondition;
import com.mini.conditon.ChanceBaseInfoCondition;
import com.mini.conditon.TraditionChanceCondition;
import com.mini.config.BusinessException;
import com.mini.config.CheckLogin;
import com.mini.constant.RedisKeyConst;
import com.mini.model.*;
import com.mini.service.BusinessBigLessonOrderService;
import com.mini.service.BusinessTraditionChanceService;
import com.mini.service.ChanceCommentService;
import com.mini.service.ChanceUserProfileService;
import com.mini.sign.SignUtil;
import com.mini.util.BeanPropertiesUtil;
import com.mini.util.CalendarUtil;
import com.mini.util.ExcelUtil;
import com.mini.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.mini.vo.CommonResultMessage.contact_repeat;
import static java.util.Calendar.DATE;

/**
 * @author shixiaopeng  on 2020/12/2
 */
@RestController
@RequestMapping("/tradition/chance")
@Slf4j
@Api(tags = "传统机会相关")
public class BusinessTraditionChanceController extends BaseController implements BeanPropertiesUtil {

    @Autowired
    private BusinessTraditionChanceService businessTraditionChanceService;
    @Autowired
    private ChanceCommentService chanceCommentService;
    @Autowired
    private ChanceUserProfileService chanceUserProfileService;
    @Autowired
    private BusinessBigLessonOrderService businessBigLessonOrderService;


    @CheckLogin
    @ApiOperation(value = "机会详情", notes = "机会详情")
    @GetMapping("/{chanceId}")
    public BusinessResult<BusinessTraditionChanceVO> chanceInfo(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @PathVariable("chanceId") Long chanceId) {
        BusinessTraditionChance one = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(one)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR);
        }
        BusinessTraditionChanceVO businessTraditionChanceVO = businessTraditionChanceService.transSingleVO(one, Authorization);

        //TODO 用户画像 和备注
        BusinessChanceCommentRecord commentLastedOne = chanceCommentService.findLastedRecord(chanceId);

        Map<String, BusinessChanceUserProfile> userProfileMap = chanceUserProfileService.getUserProfile(chanceId);

        businessTraditionChanceVO.setCommentLasted(commentLastedOne);
        businessTraditionChanceVO.setUserProfile(userProfileMap);

        return BusinessResult.createSuccessInstance(businessTraditionChanceVO);
    }

    @CheckLogin
    @ApiOperation(value = "系统转分配--批量")
    @PutMapping("/systemDistributeList")
    public BusinessResult handDistributeList(@ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                             @RequestBody TraditionChanceCondition traditionChanceCondition){
        traditionChanceCondition.setToken(Authorization);
        while(true){
            Page<BusinessTraditionChance> businessTraditionChancesPage = businessTraditionChanceService.searchHandle(traditionChanceCondition);
            List<BusinessTraditionChance> traditionChanceDBList = businessTraditionChancesPage.getContent();
            if(CollectionUtils.isEmpty(traditionChanceDBList)){
                break;
            }
            Integer pageNumber = traditionChanceCondition.getPageNumber();
            traditionChanceCondition.setPageNumber(pageNumber+1);

            for(BusinessTraditionChance businessTraditionChance : traditionChanceDBList){
                if(Objects.isNull(businessTraditionChance.getTeacherId())){
                    businessTraditionChanceService.handDistribute(businessTraditionChance, traditionChanceCondition.getNewTeacherId());
                }else{
                    log.info("{}", businessTraditionChance);
                    businessTraditionChanceService.convertTeacher(businessTraditionChance, traditionChanceCondition.getNewTeacherId(),Authorization,"");
                }
            }
        }
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "传统机会列表,分页", notes = "传统机会列表,分页")
    @PostMapping("/page")
    public BusinessResult<PageResultVO<BusinessTraditionChanceVO>> page(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @RequestBody TraditionChanceCondition traditionChanceCondition) {
        checkPageParams(traditionChanceCondition);
        traditionChanceCondition.setToken(Authorization);
        return BusinessResult.createSuccessInstance(businessTraditionChanceService.search(traditionChanceCondition));
    }

    @CheckLogin
    @ApiOperation(value = "导出传统机会列表", notes = "导出传统机会列表")
    @PostMapping("/export")
    public void exportAllStudents(HttpServletRequest request, HttpServletResponse response, @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
                                  @RequestBody TraditionChanceCondition traditionChanceCondition) {
        checkPageParams(traditionChanceCondition);
        traditionChanceCondition.setToken(Authorization);
        String sign = SignUtil.sign(JSON.toJSONString(traditionChanceCondition));

        String opreationLock = RedisKeyConst.getOpreationLock(sign);
        if(tryLock(opreationLock,600)){
            try{
                // 设置响应输出的头类型
                response.setHeader("content-Type", "application/vnd.ms-excel");
                String title = "传统机会列表";
                String excelFileName = title + LocalDate.now().toString()+".xlsx";
                ExportParams exportParams = new ExportParams(title, title, ExcelType.XSSF);
                Workbook workbook = bigExcel(1,traditionChanceCondition,null,exportParams);
                ExcelExportUtil.closeExportBigExcel();
                ExcelUtil.downLoadExcel(excelFileName,response,workbook);
                releaseLockKey(opreationLock);
            } catch (Exception e) {
                log.info("{}",e);
                releaseLockKey(opreationLock);
                log.error("导出文件异常", e);
            }
        }

    }

    @CheckLogin
    @ApiOperation(value = "运营侧-传统机会列表,分页", notes = "运营侧-传统机会列表,分页")
    @PostMapping("/search")
    public BusinessResult<PageResultVO<BusinessTraditionChanceVO>> search(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @RequestBody ChanceBaseCondition chanceBaseCondition) {
        log.info("运营侧查询条件{}, pageSize {}, pageNumber {}", chanceBaseCondition, chanceBaseCondition.getPageSize(), chanceBaseCondition.getPageNumber());
        checkPageParams(chanceBaseCondition);
        TraditionChanceCondition traditionChanceCondition = new TraditionChanceCondition();
        copyNonNullProperties(chanceBaseCondition, traditionChanceCondition);
        traditionChanceCondition.setChanceTimes(chanceBaseCondition.getChanceTimes());
        traditionChanceCondition.setPageNumber(chanceBaseCondition.getPageNumber());
        traditionChanceCondition.setPageSize(chanceBaseCondition.getPageSize());
        traditionChanceCondition.setToken(Authorization);

        traditionChanceCondition.setSystemFrom(ChanceBaseInfoVO.SystemFromEnum.throwSource.code);
        if(chanceBaseCondition.getToufangStatus() == 1){
            traditionChanceCondition.setSortColumn("lastFollowUpTime");
            traditionChanceCondition.setChanceStatus(ChanceBaseInfoVO.ChanceStatus.follow.code);
            traditionChanceCondition.setFollowUpStatus(TraditionChanceCondition.FollowUpEnum.VALID.code);
        }else if(chanceBaseCondition.getToufangStatus() == 2){
            traditionChanceCondition.setSortColumn("lastFollowUpTime");
            traditionChanceCondition.setChanceStatus(ChanceBaseInfoVO.ChanceStatus.entered.code);
        }else if(chanceBaseCondition.getToufangStatus() == 3){
            traditionChanceCondition.setSystemFrom(ChanceBaseInfoVO.SystemFromEnum.systemSource.code);
        }
        UserVO loginUser = getLoginUser(Authorization);
        traditionChanceCondition.setTeacherId(loginUser.getId());
        log.info("服务端查询条件 {}, pageSize {}, pageNumber {}", traditionChanceCondition, traditionChanceCondition.getPageSize(), traditionChanceCondition.getPageNumber());

        PageResultVO<BusinessTraditionChanceVO> page = businessTraditionChanceService.search(traditionChanceCondition);

        List<BusinessTraditionChanceVO> list = page.getRows();
        if(!CollectionUtils.isEmpty(list)){
            Set<Long> chanceIds = list.stream().map(BusinessTraditionChanceVO :: getId).collect(Collectors.toSet());
            Map<Long, BusinessChanceCommentRecord> lastedRecordMap = chanceCommentService.findCommentsByChanceId(chanceIds);
            Map<Long, Map<String, BusinessChanceUserProfile>> userProfileMap = chanceUserProfileService.getUserProfileMap(chanceIds);
            Map<Long, List<BusinessBigLessonOrderVO>> listMap = new HashMap<>();
            if(chanceBaseCondition.getToufangStatus() == 2){
                List<BusinessBigLessonOrderVO> businessBigLessonOrderVOS = businessBigLessonOrderService.bigOrderSimpleList(chanceIds);
                listMap = businessBigLessonOrderVOS.stream().collect(Collectors.groupingBy(o -> o.getChanceId()));
            }
            for(BusinessTraditionChanceVO chance : list){
                chance.setCommentLasted(lastedRecordMap.get(chance.getId()));
                chance.setUserProfile(userProfileMap.get(chance.getId()));
                if(listMap.containsKey(chance.getId())){
                    chance.setBigLessonOrderVO(listMap.get(chance.getId()).get(0));
                }
            }
        }
        return BusinessResult.createSuccessInstance(page);
    }

    @CheckLogin
    @ApiOperation(value = "修改基本信息功能", notes = "修改基本信息功能")
    @PutMapping("/edit")
    public BusinessResult<BusinessTraditionChanceVO> edit(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @RequestBody ChanceBaseInfoCondition chanceBaseInfoCondition) {

        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceBaseInfoCondition.getId());
        if (Objects.isNull(traditionChanceDB)) {
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }

        copyNonNullProperties(chanceBaseInfoCondition, traditionChanceDB);
        return BusinessResult.createSuccessInstance(businessTraditionChanceService.save(traditionChanceDB));

    }


    @CheckLogin
    @ApiOperation(value = "手动分配--单个")
    @PutMapping("/handDistributeOne")
    public BusinessResult handDistribute(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId,
            @ApiParam(required = true, value = "咨询师id") @RequestParam(value = "teacherId") Long teacherId){
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        if(Objects.nonNull(traditionChanceDB.getTeacherId())){
            throw new BusinessException("当前机会已分配咨询师");
        }
        businessTraditionChanceService.handDistribute(traditionChanceDB, teacherId);
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "手动分配--批量")
    @PutMapping("/handDistributeList")
    public BusinessResult handDistributeList(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id集合") @RequestParam(value = "chanceIds") List<Long> chanceIds,
            @ApiParam(required = true, value = "咨询师id") @RequestParam(value = "teacherId") Long teacherId){
        List<BusinessTraditionChance> traditionChanceDBList = businessTraditionChanceService.findByIdIn(chanceIds);
        if(Objects.isNull(traditionChanceDBList)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
//        boolean anyMatch = traditionChanceDBList.stream().anyMatch(businessTraditionChance -> businessTraditionChance.getChanceStatus().intValue() != ChanceBaseInfoCondition.ChanceStatusEnum.nodistribute.code.intValue());
//        if(anyMatch){
//            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "有机会状态不是未分配状态");
//        }


//        Date today = CalendarUtil.parseShortDate(CalendarUtil.getShortDateString(new Date()));
//        boolean match = traditionChanceDBList.stream().anyMatch(businessTraditionChance -> businessTraditionChance.getCreateTime().compareTo(today) == 1);
//        if(match){
//            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"有机会是昨天晚上12点之后的机会，不允许手动分配");
//        }
        traditionChanceDBList.forEach(businessTraditionChance -> {
            if(Objects.isNull(businessTraditionChance.getTeacherId())){
                businessTraditionChanceService.handDistribute(businessTraditionChance, teacherId);
            }else{
                businessTraditionChanceService.convertTeacher(businessTraditionChance, teacherId,Authorization,"");
            }
        });
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "手动分配--批量")
    @PostMapping("/handDistributeListPost")
    public BusinessResult handDistributeListPost(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @RequestBody ConvertTeacherParams params){
        log.info("handDistributeListPost params = {}", JSON.toJSONString(params));
        List<Long> chanceIds = params.getChanceIds();
        Long teacherId = params.getTeacherId();
        String conditionParams = params.getCondition();
        List<BusinessTraditionChance> traditionChanceDBList = businessTraditionChanceService.findByIdIn(chanceIds);
        if(Objects.isNull(traditionChanceDBList)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
//        boolean anyMatch = traditionChanceDBList.stream().anyMatch(businessTraditionChance -> businessTraditionChance.getChanceStatus().intValue() != ChanceBaseInfoCondition.ChanceStatusEnum.nodistribute.code.intValue());
//        if(anyMatch){
//            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "有机会状态不是未分配状态");
//        }


//        Date today = CalendarUtil.parseShortDate(CalendarUtil.getShortDateString(new Date()));
//        boolean match = traditionChanceDBList.stream().anyMatch(businessTraditionChance -> businessTraditionChance.getCreateTime().compareTo(today) == 1);
//        if(match){
//            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR,"有机会是昨天晚上12点之后的机会，不允许手动分配");
//        }
        traditionChanceDBList.forEach(businessTraditionChance -> {
            if(Objects.isNull(businessTraditionChance.getTeacherId())){
                businessTraditionChanceService.handDistribute(businessTraditionChance, teacherId);
            }else{
                businessTraditionChanceService.convertTeacher(businessTraditionChance, teacherId,Authorization,conditionParams);
            }
        });
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "转归属")
    @GetMapping("/convertTeacher")
    public BusinessResult convertTeacher(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId,
            @ApiParam(required = true, value = "新咨询师id") @RequestParam(value = "eacherId") Long teacherId){
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        if(traditionChanceDB.getTeacherId().longValue() == teacherId.longValue()){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "禁止转给同一个咨询师");
        }
        businessTraditionChanceService.convertTeacher(traditionChanceDB, teacherId,Authorization,"");
        return BusinessResult.createSuccessInstance(null);
    }

    @CheckLogin
    @ApiOperation(value = "转归属记录列表")
    @GetMapping("/convertRecord")
    public BusinessResult<List<BusinessChanceConvertRecord>> convertRecord(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId){
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        List<BusinessChanceConvertRecord> convertRecords = businessTraditionChanceService.convertRecord(chanceId);
        convertRecords.forEach(businessChanceConvertRecord -> {
            businessChanceConvertRecord.setTime(businessChanceConvertRecord.getCreateTime());
        });
        return BusinessResult.createSuccessInstance(convertRecords);
    }


    @ApiOperation(value = "拨打电话后，信息通知给机会--服务内部调用")
    @PostMapping("/callInfo")
    public BusinessResult callInfo(@RequestHeader("sig") String sig,
            @RequestBody BusinessCallInfoVO callInfoVO){
        log.info("外呼回调 {}", callInfoVO);
        if(!(checkSign(sig))){
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }
        //被叫号码
        String callee = callInfoVO.getCallee();
        BusinessChancePhone chancePhone = businessTraditionChanceService.findPhone(businessTraditionChanceService.encryptPhone(callee));
        if(Objects.isNull(chancePhone)){
            log.info("手机号不存在，不做处理 {}", callInfoVO);
            return BusinessResult.createSuccessInstance(null);
        }
        businessTraditionChanceService.updatePhoneRecord(chancePhone, callInfoVO);
        return BusinessResult.createSuccessInstance(null);
    }

    @ApiOperation(value = "根据手机号查询机会信息")
    @GetMapping("/chanceInfoByPhone")
    public BusinessResult<BusinessChancePhone> chanceInfoByPhone(@RequestHeader("sig") String sig,
                                   @ApiParam(required = true, value = "手机号") @RequestParam(value = "phone") Long phone){
        if(!(checkSign(sig))){
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }
        //加密后查询
        String encryptPhone = businessTraditionChanceService.encryptPhone(phone+"");
        BusinessChancePhone chancePhone = businessTraditionChanceService.findPhone(encryptPhone);
        if(Objects.isNull(chancePhone)){
            throw new BusinessException("手机号不存在");
        }
        return BusinessResult.createSuccessInstance(chancePhone);
    }

    @ApiOperation(value = "更新机会状态--服务内部调用,-1:未分配 0：未跟进 1:跟进中 2:已报名")
    @PutMapping("/updateStatus/{chanceId}")
    public BusinessResult updateStatus(@RequestHeader("sig") String sig,
                                       @PathVariable("chanceId") Long chanceId,
                                       @ApiParam(required = true, value = "机会状态") @RequestParam(value = "status") Integer status){
        if(!(checkSign(sig))){
            return BusinessResult.createInstance(CommonResultMessage.SIGN_ERROR);
        }


        businessTraditionChanceService.updateChanceStatus(chanceId, status);

        return BusinessResult.createSuccessInstance(null);
    }


    @CheckLogin
    @ApiOperation(value = "添加手机号")
    @GetMapping("/addPhone")
    public BusinessResult<BusinessChancePhone> addPhone(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId,
            @ApiParam(required = true, value = "手机号") @RequestParam(value = "phone") Long phone){
        BusinessChancePhone chancePhone = businessTraditionChanceService.findPhone(businessTraditionChanceService.encryptPhone(phone + ""));
        if(Objects.nonNull(chancePhone)){
            log.info("该手机号已添加过{}", chancePhone);
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "手机号已撞单，请重新添加新的手机号");
        }
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        List<BusinessChancePhone> phoneList = traditionChanceDB.getPhoneList();
        if(Objects.nonNull(phoneList) && phoneList.size() == 2){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "当前机会已有两个手机号");
        }
        BusinessChancePhone businessChancePhone = businessTraditionChanceService.addPhone(traditionChanceDB, phone);
        String realPhone = businessTraditionChanceService.decryptPhone(businessChancePhone.getPhone());
        log.info("realPhone {}", realPhone);

        BusinessChancePhone result = new BusinessChancePhone();
        copyNonNullProperties(businessChancePhone, result);
        result.setRealPhone(realPhone);
        result.setCreateTime(new Date());
        result.setTimestamp(result.getCreateTime().getTime());
        result.setPhone(realPhone.replace(realPhone.substring(3, 7), "*****"));
        return BusinessResult.createSuccessInstance(result);
    }


    @CheckLogin
    @ApiOperation(value = "添加微信号")
    @GetMapping("/addWechatNo")
    public BusinessResult addWechatNo(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId,
            @ApiParam(required = true, value = "微信号") @RequestParam(value = "wechatNo") String wechatNo){
        if(StringUtils.isEmpty(wechatNo)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "微信号不能为空");
        }
        BusinessChanceWechat chanceWechat = businessTraditionChanceService.findWechatNo(wechatNo);
        if(Objects.nonNull(chanceWechat)){
            //撞单情况
            return BusinessResult.createSuccessInstance(contact_repeat);
        }
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        List<BusinessChanceWechat> wechatList = traditionChanceDB.getWechatList();
        if(Objects.nonNull(wechatList) && wechatList.size() == 2){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "当前机会已有两个微信号");
        }
        BusinessChanceWechat businessChanceWechat = businessTraditionChanceService.addWechatNO(traditionChanceDB, wechatNo);

        BusinessChanceWechat result = new BusinessChanceWechat();
        copyNonNullProperties(businessChanceWechat, result);
        result.setRealWechatNo(wechatNo);
        result.setCreateTime(new Date());
        result.setTimestamp(result.getCreateTime().getTime());
        StringBuffer wechatNoStr = new StringBuffer(wechatNo);
        result.setWechatNo(wechatNoStr.replace(3, wechatNo.length(), "****").toString());
        return BusinessResult.createSuccessInstance(result);
    }


    @CheckLogin
    @ApiOperation(value = "验证好友关系")
    @GetMapping("/checkRelation")
    public BusinessResult<BusinessChanceWechat> checkRelation(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "机会id") @RequestParam(value = "chanceId") Long chanceId,
            @ApiParam(required = true, value = "微信号") @RequestParam(value = "wechatNo") String wechatNo){
        BusinessTraditionChance traditionChanceDB = businessTraditionChanceService.findOne(chanceId);
        if(Objects.isNull(traditionChanceDB)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "根据id查询不到当前数据");
        }
        List<BusinessChanceWechat> wechatList = traditionChanceDB.getWechatList();
        List<BusinessChanceWechat> chanceWechats = wechatList.stream().filter(businessChanceWechat -> businessChanceWechat.getWechatNo().equals(wechatNo)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(chanceWechats)){
            return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "当前机会没有这个微信号");
        }
        return BusinessResult.createSuccessInstance(businessTraditionChanceService.getRelation(traditionChanceDB, chanceWechats.get(0), wechatNo));
    }


    @CheckLogin
    @ApiOperation(value = "加微记录列表")
    @GetMapping("/addWechatRecord")
    public BusinessResult<List<BusinessWechatOperateRecord>> addWechatRecord(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "微信号") @RequestParam(value = "wechatNo") String wechatNo){
        return BusinessResult.createSuccessInstance(businessTraditionChanceService.addWechatRecord(wechatNo));
    }

    @CheckLogin
    @ApiOperation(value = "微信名片信息")
    @GetMapping("/wechatInfo")
    public BusinessResult<BusinessChanceWechat> wechatInfo(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "微信号") @RequestParam(value = "wechatNo") String wechatNo){
        return BusinessResult.createSuccessInstance(businessTraditionChanceService.wechatInfo(wechatNo));
    }

    @CheckLogin
    @ApiOperation(value = "联系方式在前端置顶展示")
    @GetMapping("/frontDiaplay")
    public BusinessResult<String> frontDiaplay(
            @ApiParam(value = "token", required = true) @RequestHeader String Authorization,
            @ApiParam(required = true, value = "类型，0手机号，1微信号") @RequestParam(value = "type") Integer type,
            @ApiParam(required = true, value = "联系方式") @RequestParam(value = "contact") String contact){
        if(type == 0){
            BusinessChancePhone businessChancePhone = businessTraditionChanceService.findPhone(businessTraditionChanceService.encryptPhone(contact));
            if(Objects.isNull(businessChancePhone)){
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "该手机号不存在");
            }
            businessTraditionChanceService.frontDiaplayPhone(businessChancePhone);
            return BusinessResult.createSuccessInstance(null);
        } else {
            BusinessChanceWechat businessChanceWechat = businessTraditionChanceService.findWechatNo(contact);
            if(Objects.isNull(businessChanceWechat)){
                return BusinessResult.createInstance(CommonResultMessage.PARAMS_ERROR, "该微信号不存在");
            }
            businessTraditionChanceService.frontDiaplayWechatNo(businessChanceWechat);
            return BusinessResult.createSuccessInstance(null);
        }
    }

    private Workbook bigExcel(int currentPage, TraditionChanceCondition condition, Workbook workbook, ExportParams exportParams) {
        //分页查询数据
        int pageSize = 5000;
        condition.setPageNumber(currentPage);
        condition.setPageSize(pageSize);
        PageResultVO<BusinessTraditionChanceVO> page = businessTraditionChanceService.search(condition);

        workbook = ExcelExportUtil.exportBigExcel(exportParams, BusinessTraditionChanceVO.class, page.getRows());

        long totalCount = page.getTotal();
        int totalPage = (int)Math.ceil( (float) totalCount / pageSize );

        //如果不是最后一页，递归查询
        if (totalPage > currentPage) {
            bigExcel(currentPage + 1, condition, workbook, exportParams);
        }
        return workbook;
    }
}
